<template>
    <div>
        <div class="filter-container">
            <el-form label-position="left" :inline="true">
                <el-form-item title="日期" prop="day" label="日期">
                    <picker-date-range v-model="search.day" :clearable="false"></picker-date-range>
                </el-form-item>
                <el-form-item label="留存" placeholder="">
                    <el-select v-model="search.dayType" style="width: 80px">
                        <el-option :label="`${item.label}`" :value="item.value" :key="index" v-for="(item, index) in options.dayType.list"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="图表类型" placeholder="">
                    <el-select v-model="search.chartType" style="width: 100px" @change="chartTypeChanged">
                        <el-option :type="search.chartType" :label="`${item.label}`" :value="item.value" :key="index" v-for="(item, index) in options.chartType.list"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="渠道类型" v-show="displayType">
                    <select-app-source-type v-model="search.sourceType" :multiple="true"></select-app-source-type>
                </el-form-item>
                <el-form-item label="渠道" v-show="displaySource">
                    <select-app-source v-model="search.source" :type="search.sourceType" :multiple="true"></select-app-source>
                </el-form-item>
                <el-form-item label="优化师" prop="spreadUser">
                    <select-spread-user v-model="search.spreadUser" :multiple="true"></select-spread-user>
                </el-form-item>
                <el-form-item label="">
                    <el-button class="filter-item" icon="el-icon-search" type="primary" :loading="loading" @click="initSearch()">搜索</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div id="pay-register-chart" :style="'width: 100%; margin-bottom: 10px;;min-height: '+maxHeight+'px;'"></div>
    </div>
</template>

<script>
import SelectAppSourceType from '~/components/Select/app-source-type';
import SelectSpreadUser from '~/components/Select/spread-user';
import echarts from "echarts";

export default {
    components: {
        SelectAppSourceType,
        SelectSpreadUser,
    },
    props: {
    },
    data() {
        return {
            search: {
                source: '',
                sourceType: '',
                spreadUser: '',
                day: [],
                dayType: 1,
                chartType: 1,
            },
            loading: false,
            selected: [],
            chartData: [],
            options: this.$store.state.spreadData.options,
            sourceTypeOptions: this.$store.state.appSource.options.type,
            days: [],
            displayType: true,
            displaySource: true,

            echartsInstance: null,
            echartsOption: {
                legend: {
                    data: [],
                    selected: {},
                    type: 'scroll',
                    orient: 'horizontal',  // 图例列表的布局朝向
                    left: 180,
                    right: 200,  // 图例组件离容器右侧的距离
                    top: 10,  // 图例组件离容器顶部的距离
                    bottom: 20,  // 图例组件离容器底部的距离
                    pageButtonItemGap: 5,  // 翻页按钮之间的间隔
                    pageButtonGap: 10,  // 图例与翻页按钮之间的间隔
                    pageButtonPosition: 'end',  // 翻页按钮靠近哪端
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                title: {
                    text: '走势图'
                },
                tooltip: {
                    trigger: 'axis',
                },
                toolbox: {
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        restore: {},
                        saveAsImage: {},
                    }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: true,
                },
                yAxis: {
                    type: 'value',
                    axisLabel: {  // 显示百分比
                        show: true,
                        interval: 'auto',
                        formatter: '{value} %'
                    },
                    show: true,
                    scale: true,
                    boundaryGap: [0, '100%'],
                    max: 100,
                    min: 0
                },
                series: [],
                dataZoom: [{
                    type: 'inside',
                    start: 0,
                    end: 100
                }, {
                    start: 0,
                    end: 100
                }],
            },
            resizeTimeout: null,
            echartsLoading: {
                text: '数据加载中...',
                color: '#c23531',
                textColor: '#000',
                maskColor: 'rgba(255, 255, 255, 0.8)',
                zlevel: 0
            }
        }
    },
    computed: {
        maxHeight() {
            return this.$store.state.backend.windowInnerHeight - 240;
        },
    },
    methods: {
        handleSearch() {
            this.loading = true;
            let filter = Object.assign({}, this.search, {
                field: this.field,
            });
            this.$store.dispatch('spreadData/UserKeepChart', filter).then(({data}) => {
                this.days = data.days;
                this.chartData = data.data;
                this.setChartOptions();
            }).finally(() => {
                this.loading = false;
            });
        },
        initData() {
            this.initSearchDate();
            this.handleSearch();
        },
        initSearchDate() {
            this.search.day = [
                moment().add(-1, 'M').startOf('d').unix(),
                moment().add(-1, 'd').endOf('d').unix(),
            ];
        },
        initSearch() {
            this.echartsInstance.showLoading(this.echartsLoading);
            this.handleSearch();
        },

        setChartOptions() {
            this.initChartOptions();
            let xAxisData = [];
            let series = [];
            let legend = [];

            xAxisData = this.days;

            const source = {};
            this.$store.state.appSource.all.forEach(item => {
                source[item.id] = item.name;
            });

            Object.entries(this.chartData).forEach(([index, item]) => {
                let lineName = ''
                if (this.search.chartType === 2) {
                    if (!this.sourceTypeOptions[index]) {
                        return;
                    }
                    lineName = this.sourceTypeOptions[index].label;
                } else if (this.search.chartType === 3) {
                    lineName = source[index];
                } else {
                    lineName = index
                }
                legend.push(lineName)
                series.push({
                    name: lineName,
                    type: 'line',
                    data: Object.values(item.data).map((item) => {
                        return (item * 100).toFixed(2)
                    }),
                    itemStyle: {
                        normal: {
                            label: {
                                show: true,
                                formatter: function (a) {
                                    return a.data + "%";
                                }
                            }
                        }
                    },
                })
            })
            // 重新设置 不然数据会串
            let echartsOption = this.echartsOption;
            echartsOption.legend.data = legend;
            echartsOption.xAxis.data = xAxisData;
            echartsOption.series = series;
            this.echartsInstance.setOption(echartsOption, true);
            this.echartsInstance.hideLoading()
        },
        initChart() {
            this.echartsInstance = echarts.init(document.getElementById('pay-register-chart'));
            this.initChartOptions();
            this.echartsInstance.showLoading(this.echartsLoading);
            this.echartsInstance.on('click', function (params) {
                console.log(params);
            });
        },
        initChartOptions() {
            this.echartsOption.title.text = (this.search.dayType === 1 ? "次" : this.search.dayType) + "日付费留存"
            this.echartsOption.series = [];
            this.echartsOption.legend.data = [];
            this.echartsOption.xAxis.data = [];
            this.echartsInstance.setOption(this.echartsOption);
        },
        chartTypeChanged(value) {
            // 切换图表类型时，清除渠道和渠道类型缓存，重新进行选择
            this.search.sourceType = this.search.source = ''
            if (value === 2) {
                this.displayType = true
                this.displaySource = false
            } else if (value === 3) {
                this.displayType = false
                this.displaySource = true
            } else {
                this.displayType = this.displaySource = true
            }
        },
    },
    created() {
        this.initData();
    },
    mounted() {
        this.initChart()
    },
    beforeDestroy() {
        this.echartsInstance.clear();
    }
}
</script>

<style lang="scss" scoped>
#app .el-form-item {
    margin-bottom: 10px;
}
</style>

